package export

import (
	"fmt"

	"github.com/jinzhu/gorm"
)

type CarotidNidusInfo struct {
	*NidusExtInfo
	CheckStatus        uint32  `json:"checkStatus" gorm:"Column:checkStatus"`
	ImageIsDelete      uint16  `json:"imageIsDelete" gorm:"Column:imageIsDelete"`
	VerticalDiameter   float32 `json:"verticalDiameter" gorm:"Column:verticalDiameter"`     //斑块厚度
	BloodDiameter      float32 `json:"bloodDiameter" gorm:"Column:bloodDiameter"`           //官腔内径
	StenosisRate       float32 `json:"stenosisRate" gorm:"Column:stenosisRate"`             //狭窄率
	HorizontalDiameter float32 `json:"horizontalDiameter" gorm:"Column:horizontalDiameter"` //斑块长度
	Echogenicity       int     `json:"echogenicity" gorm:"Column:echogenicity"`             //回声类型
	EchogenicityGrade  int     `json:"echogenicityGrade" gorm:"Column:echogenicityGrade"`   //回声等级
	FibrousCap         int     `json:"fibrousCap" gorm:"Column:fibrousCap"`                 //纤维帽
	Edge               int     `json:"edge" gorm:"Column:edge"`                             //边缘
	Calcification      int     `json:"calcification" gorm:"Column:calcification"`           //钙化
	Uclcer             int     `json:"uclcer" gorm:"Column:uclcer"`                         //溃疡
	X1                 int     `json:"x1" gorm:"Column:x1"`
	Y1                 int     `json:"y1" gorm:"Column:y1"`
	X2                 int     `json:"x2" gorm:"Column:x2"`
	Y2                 int     `json:"y2" gorm:"Column:y2"`
}

/**
 * @brief 获取颈动脉病灶数据
 * @param db-数据库操作引擎
 * @param patientIds-患者ID集合
 * @return 病灶数据集合，错误信息
 */
func GetCarotidExportData(db *gorm.DB, patientIds string) ([]*CarotidNidusInfo, error) {
	return getCarotidExportData(db, patientIds, "t_plaque_info")
}

/**
 * @brief 获取颈动脉病灶AI原始数据
 * @param db-数据库操作引擎
 * @param patientIds-患者ID集合
 * @return 病灶数据集合，错误信息
 */
func GetCarotidExportDataAi(db *gorm.DB, patientIds string) ([]*CarotidNidusInfo, error) {
	return getCarotidExportData(db, patientIds, "t_plaque_info_ai")
}

func getCarotidExportData(db *gorm.DB, patientIds, tbn string) ([]*CarotidNidusInfo, error) {
	var nidus []*CarotidNidusInfo

	var query string
	query = "SELECT t1.patient_name, t1.check_id, t1.patient_id, t1.timeStamp, t1.sex, t1.age, t2.imageNTPStamp, t2.checkStatus, t2.isDelete as imageIsDelete, "
	query += "t3.verticalDiameter, t3.bloodDiameter, t3.stenosisRate, t3.horizontalDiameter, t3.echogenicity, t3.echogenicityGrade, t3.fibrousCap, t3.edge, t3.calcification, "
	query += "t3.uclcer, t3.x1, t3.y1, t3.x2, t3.y2"
	query += " FROM t_patient_info t1"
	query += " LEFT JOIN t_image_info t2 on t1.id=t2.patientId"
	query += fmt.Sprintf(" INNER JOIN %s t3 on t2.id=t3.imageId and t1.id=t3.patientId", tbn)
	//导出患者ID
	query += fmt.Sprintf(" WHERE t1.id in (%s)", patientIds)

	res := db.Raw(query).Scan(&nidus)
	if res.Error != nil {
		return nil, res.Error
	}

	return nidus, nil
}
